<template>
  <div id="container">
    <el-button type="success" @click="remove">删除自定义Maker</el-button>
  </div>
</template>

<script>
import bus from "@/eventBus/eventBus.js";

import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  securityJsCode: "85535c2dd4dfd485f678622d47c7758c",
};

export default {
  data() {
    return {
      map: null,
      autoOptions: {
        input: "",
      },
      auto: null,
      placeSearch: null,
      searchPlaceInput: "", //search输入框传递过来的关键字；
      district: null,
      polygons: [],
      showHerat: false,
      heatmap: null,
      heatmapList: null,
      Markers: null,
    };
  },
  created() {
    console.log(66);
    bus.$on("shareUserInput", (val) => {
      console.log("接受到的值是", val);

      this.autoOptions.input = val.inputId;
      this.searchPlaceInput = val.userInput;
    });

    bus.$on("shareHeartMapShow", (val) => {
      console.log("显示状态是", val);

      this.showHerat = val;
    });
  },
  watch: {
    searchPlaceInput(newVal) {
      console.log("////////", newVal);
      if (newVal.trim().length != 0) {
        this.placeSearch.search(newVal);
        this.map.setZoom(16, true, 1);
        this.drawBounds(newVal);
      } else {
        this.successTitle("请输入相关查询信息！", "warning");
      }
    },
    showHerat(newVal) {
      if (newVal) {
        this.showHeartMap();
      } else {
        console.log("关闭了");
        this.heatmap.hide(); //调用这个hide api 关闭热力图层显示；
      }
    },
  },
  mounted() {
    //DOM初始化完成进行地图初始化
    this.initMap();
    //console.log(666);
  },
  methods: {
    initMap() {
      AMapLoader.load({
        key: "675e6caa8aa8124cf14acc022f99caf0", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.Scale",
          "AMap.HawkEye",
          "AMap.Geolocation",
          "AMap.MapType",
          "AMap.AutoComplete",
          "AMap.PlaceSearch",
          "AMap.Geocoder",
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.map = new AMap.Map("container", {
            //设置地图容器id
            viewMode: "3D", //是否为3D地图模式
            zoom: 10, //初始化地图级别
            center: [121.473667, 31.230525], //初始化地图中心点位置
          });
          this.map.addControl(new AMap.Scale()); //new一个比例尺控件的实例化对象；
          this.map.addControl(new AMap.HawkEye()); //new一个地图鹰眼控件的实例化对象
          this.map.addControl(new AMap.Geolocation()); //new一个地图鹰眼控件的实例化对象
          this.map.addControl(new AMap.MapType());
          this.auto = new AMap.AutoComplete(this.autoOptions);
          this.placeSearch = new AMap.PlaceSearch({
            map: this.map,
          }); //构造地点查询类
          this.auto.on("select", this.select);
          this.map.on("click", (e) => {
            console.log("tets");
            //调用逆向地理编码方法
            let lat = e.lnglat.lat;
            let lng = e.lnglat.lng;
            this.getLngService(lat, lng);
          });
          //添加固定点标记；
          let marker1 = new AMap.Marker({
            position: new AMap.LngLat(121.473667, 31.230525),
            anchor: "bottom-center",
            title: "上海",
          });
          this.map.add(marker1);

          var icon = new AMap.Icon({
            size: new AMap.Size(40, 40),
            image: require("@/assets/maker.png"),
            // imageOffset: new AMap.Pixel(0, -60), //图标的偏移量范围
            imageSize: new AMap.Size(40, 40),
          });
          // 自定义点标记的实现
          let definedMaker = new AMap.Marker({
            position: new AMap.LngLat(121.173667, 31.130525),
            anchor: "bottom-center",
            title: "自定义点标记",
            icon: icon,
          });
          this.map.add(definedMaker);

          //圆形标记的展示；

          let CircleMarker = new AMap.CircleMarker({
            center: new AMap.LngLat(121.973667, 31.530525),
            radius: 10,
            fillColor: "#f54b1d",
            strokeColor: "#f54b1d",
          });
          this.map.add(CircleMarker);
        })
        .catch((e) => {
          //  console.log(e);
        });
    },
    select(e) {
      this.placeSearch.setCity(e.poi.adcode);
      this.placeSearch.search(e.poi.name); //关键字查询查询
      //this.map.setZoom(10);
      this.map.setZoom(16, true, 1);
      this.drawBounds(e.poi.name);
      console.log(e.poi.name);
    },

    // 行政区区域划分
    drawBounds(newValue) {
      //加载行政区划插件
      if (!this.district) {
        //实例化DistrictSearch
        var opts = {
          subdistrict: 0, //获取边界不需要返回下级行政区
          extensions: "all", //返回行政区边界坐标组等具体信息
          level: "district", //查询行政级别为 市
        };

        this.map.plugin(["AMap.DistrictSearch"], () => {
          this.district = new AMap.DistrictSearch(opts);
        });
        // this.district = new AMap.DistrictSearch(opts)
      }
      //行政区查询
      this.district.search(newValue, (status, result) => {
        if (result != null) {
          this.successTitle("区域位置查询成功！", "success");

          if (this.polygons != null) {
            this.map.remove(this.polygons); //清除上次结果
            this.polygons = [];
          }
          var bounds = result.districtList[0].boundaries;
          if (bounds) {
            for (var i = 0, l = bounds.length; i < l; i++) {
              //生成行政区划polygon
              var polygon = new AMap.Polygon({
                strokeWeight: 1,
                path: bounds[i],
                fillOpacity: 0.4,
                fillColor: "#80d8ff",
                strokeColor: "#0091ea",
              });
              this.polygons.push(polygon);
            }
          }
          this.map.add(this.polygons);
          this.map.setFitView(this.polygons); //视口自适应
        } else {
          this.successTitle("区域位置查询失败！", "error");
        }
      });
    },

    successTitle(mes, feedBackType) {
      this.$message({
        showClose: true,
        message: mes,
        type: feedBackType,
      });
    },
    showHeartMap() {
      this.map.plugin(["AMap.PlaceSearch"], () => {
        //构造地点查询类
        var placeSearch = new AMap.PlaceSearch({
          pageSize: 50, // 单页显示结果条数
          pageIndex: 1, // 页码
          city: this.searchPlaceInput, // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          //map: this.map, // 展现结果的地图实例
          // panel: 'panel', // 结果列表将在此容器中进行展示。
          // autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        //关键字查询
        placeSearch.search("医院", (status, result) => {
          // console.log(result)

          this.getHotChartPos("医院", result);
        });
      });
      this.$notify({
        title: "成功",
        message: "热力图获取成功，但是由于电脑性能，我们仅加载部分数据",
        type: "success",
      });
    },
    getHotChartPos(detail, result) {
      console.log("=========", result);

      let lengthSize = result.poiList.pageSize;
      const count = result.poiList.count;
      // const lengthPage = count / lengthSize  lengthSize=》表示搜索热力图的页数；
      if (lengthSize > count) {
        lengthSize = count;
      }
      for (var n = 0; n < lengthSize; n++) {
        // this.map.plugin(['AMap.PlaceSearch'], () => {
        //构造地点查询类
        var realSearch = new AMap.PlaceSearch({
          pageSize: lengthSize, // 单页显示结果条数
          pageIndex: n + 1, // 页码
          city: this.searchPlaceInput, // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          // map: this.map, // 展现结果的地图实例
          // panel: 'panel', // 结果列表将在此容器中进行展示。
          // autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
        realSearch.search(detail, (status, result) => {
          console.log("热力图查询条件", detail);
          //console.log("查询结果", result);
          // console.log("状态值", status);
          // for (var j = 0; j < 50; j++) {
          // this.map.remove(this.map.getAllOverlays('marker'))
          //var centerPoint = [result.poiList.pois[j].location.lng, result.poiList.pois[j].location.lat]
          // console.log(result)
          //热力图
          this.showHatChart(result); //处理完坐标之后会调用这个showHatChart方法来展示结果；
          // }
        });
      }
    },
    showHatChart(result) {
      console.log("查询结果哈哈哈", result);
      var info = []; //info 表示对热力图进行渲染， count表示渲染的强度；

      for (let i = 0; i < result.poiList.pageSize; i++) {
        info.push({
          lng: result.poiList.pois[i].location.lng, //这里表示对热力图区域动态添加经度
          lat: result.poiList.pois[i].location.lat, //这里表示对热力图区域动态添加纬度
          count: 3 * 6.4 * Math.round(Math.random() * (10 - 2) + 2),
        });
      }
      console.log("坐标数组是", info);

      this.map.plugin(["AMap.HeatMap"], () => {
        // console.log('nn')
        //初始化heatmap对象
        this.heatmap = new AMap.HeatMap(this.map, {
          radius: 56, //给定半径
          opacity: [0, 0.5],
          /*,
            gradient:{
                0.5: 'blue',
                0.65: 'rgb(117,211,248)',  <<=========表示渲染热力图的颜色 不设置则表示默认的；
                0.7: 'rgb(0, 255, 0)',
                0.9: '#ffea00',
                1.0: 'red'          
            }
             */
        });
        //设置数据集
        this.heatmap.setDataSet({
          data: info,
          max: 100,
        });
        this.heatmapList.push(this.heatmap);
        this.heatmap.show();
      });
    },
    //逆向地理编码服务
    getLngService(lat, lng) {
      // console.log("点击拿到的地理坐标是", lat, lng);
      let pos = [lng, lat];

      let lnglat = new AMap.LngLat(lng, lat);
      //  lat 表示维度，lng表示经度
      let geocoder = new AMap.Geocoder({
        city: "全国", //城市设为北京，默认：“全国”
      });

      // 点击地图任意位置生成一个maker
      // 将位置转换为坐标点====》位置信息
      // 根据位置信息搜索获取详细信息；
      //  声明一个maker标记点
      this.Markers = new AMap.Marker({
        position: new AMap.LngLat(lng, lat),
        icon: require("@/assets/maker.png"),
      });

      this.map.add(this.Markers);
      console.log("标记点是", Markers);
      geocoder.getAddress(lnglat, (status, result) => {
        if (status === "complete" && result.regeocode) {
          let address = result.regeocode.formattedAddress;
          console.log(address);
          let res = {
            pos: pos,
            address: address,
          };
          //  console.log(res);
          bus.$emit("shareAddress", res);
        } else {
          log.error("根据经纬度查询地址失败");
        }
      });
    },
    // 删除自定义标记的点

    remove() {
      console.log("000000");
      this.map.remove(this.Markers);
    },
  },
};
</script>

<style lang="less" scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 100%;
  button {
    position: relative;
    z-index: 99999;
  }
}
</style>